// src/components/commendModal.jsx
'use client';
import React, {useEffect, useRef, useState} from 'react';
import {useOpenStore} from "@/hooks/forum/use-open-store";
import Modal from 'react-modal'
import {EmojiHappyIcon, PhotographIcon, XIcon} from "@heroicons/react/outline";
import {usePostIdStore} from "@/hooks/forum/use-post-store";
import {format, formatDistanceToNow} from "date-fns";
import {usePathname, useRouter} from "next/navigation";
import {BACKEND_BATH_URL} from "@/lib/constants";
import {useCurrentUser} from "@/hooks/use-current-user";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import zhCN from "date-fns/locale/zh-CN";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";
import {formatDateToNow} from "@/lib/format";
import Preview from "@/components/learn/preview";

const CommendModal = () => {
    const {open, setOpen} = useOpenStore()
    const {postId, setPostId} = usePostIdStore()
    const pathname = usePathname();
    const [post, setPost] = useState(null)

    useEffect(() => {
        (async () => {
            if (pathname.replaceAll('/forum', '') !== '')
                setPostId(pathname.slice(
                    pathname.lastIndexOf('/') + 1
                ))
            if (!postId) return
            // const postFetch = await fetch(`${BACKEND_BATH_URL}/posts/${postId}`)
            const postFetch = await fetch(`/api/posts/${postId}`)
            const p = await postFetch.json()
            setPost(p.post)
        })()
    }, [postId])

    const [value, setValue] = useState('')
    const [loading, setLoading] = useState(false)
    const [selectedFileBase64, setSelectedFileBase64] = useState(null)
    const [selectedFile, setSelectedFile] = useState(null)
    const filePickerRef = useRef(null)

    const user = useCurrentUser()
    if (!user) return <div>loading...</div>
    const userId = user?.id
    const router = useRouter()

    const {mutate: uploadImg, isPending} = useGenerateUploadUrl();
    const sendComment = async () => {
        if (loading) return
        setLoading(true)

        let url
        if (selectedFile) {
            url = await uploadImg({
                // @ts-ignore
                image: selectedFile,
                prefix: post.id
            })
        }

        let comment = {
            postId: post?.id,
            userId: userId,
            comment: value,
            username: user?.name,
            name: user?.name,
            userImg: user?.image,
            // timestamp: Date.now(),
            timestamp: new Date(),
            // img: selectedFileBase64
        }
        if (url) comment = {...comment, img: url}

        // json-server
        // await fetch(`${BACKEND_BATH_URL}/comments`, {
        await fetch(`/api/comments`, {
            method: 'POST',
            body: JSON.stringify(comment),
            headers: {
                "Content-Type": "application/json",
            }
        })

        setOpen(false)
        setValue('')
        setSelectedFile(null)
        setSelectedFileBase64(null)
        setLoading(false)
        router.push(`/forum/posts/${postId}`)
        router.refresh()
    }
    const addImageToComment = (e) => {
        // 保存文件, 用于上传
        setSelectedFile(e.target.files[0])

        // 转base64用于预览
        const reader = new FileReader()
        reader.onload = (readerEvent) => {
            // console.log(readerEvent.target.result)
            setSelectedFileBase64(readerEvent.target.result)
        }
        if (e.target.files[0]) {
            reader.readAsDataURL(e.target.files[0])
        } else {
            console.error('No file selected');
        }
    }

    return (
        <div>
            {open && (
                <Modal
                    isOpen={open}
                    onRequestClose={() => setOpen(false)}
                    className={`overflow-auto max-w-lg w-[90%] absolute top-24 left-[50%] translate-x-[-50%] bg-white
                    border-2 border-gray-200 rounded-xl shadow-md h-[360px]`}
                    // border-2 border-gray-200 rounded-xl shadow-md h-[300px]`}
                >
                    <div className={`p-1`}>
                        <div className={`border-b border-gray-200 py-2 px-1.5`}>
                            <div onClick={() => setOpen(false)}
                                 className={`hoverEffect size-10 flex items-center justify-center`}>
                                {/*<XIcon className={`h-[23px] p-0 text-gray-700`}/>*/}
                                <XIcon className={`h-11 p-0 text-gray-700`}/>
                            </div>
                        </div>
                        <div className={`p-2 flex items-center space-x-1 relative`}>
                            {/*连接头像的竖线*/}
                            <span className={`w-0.5 h-full z-[-1] absolute left-8 top-11 bg-gray-300`}></span>
                            {/*当前帖子用户头像*/}
                            <Avatar className={`size-11 mr-2 rounded-full`}>
                                <AvatarImage className={`rounded-full`} src={post?.userImg}/>
                                <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                                    {post?.username && post?.username.charAt(0).toUpperCase()}
                                </AvatarFallback>
                            </Avatar>
                            {/*<img className={`size-11 rounded-full mr-4`}*/}
                            {/*     src={post?.userImg} alt="user-img"/>*/}
                            <h4 className={`font-bold text-[15px] sm:text-[16px] 
                        hover:underline`}>{post?.name}</h4>
                            <span className={`text-sm sm:text-[15px]`}
                            >@{post?.username} - </span>
                            <span className={`text-sm sm:text-[15px] hover:underline`}>
                            {/*{post.timestamp && format(parseInt(post?.timestamp), 'yyyy-MM-dd')}*/}
                                {/*    {post.timestamp && `${formatDistanceToNow((post?.timestamp), {*/}
                                {/*        locale: zhCN*/}
                                {/*    })}前`}*/}
                                {post.timestamp && `${formatDateToNow((post?.timestamp))}前`}
                                {/*{post?.timestamp}*/}
                            </span>
                        </div>
                        {/*<p className={`text-gray-500 text-[15px] sm:text-[16px]*/}
                        {/*ml-16 mb-2`}>{post?.text}</p>*/}
                        <Preview
                            className={`text-gray-500 text-[15px] sm:text-[16px]
                        ml-16 mb-2`}
                            value={(post.text)}/>

                        <div className={'flex border-b border-gray-200 p-3 space-x-3'}>
                            {/*当前登录用户头像*/}
                            <Avatar className={`size-11 rounded-full`}>
                                <AvatarImage className={`rounded-full`} src={user.image}/>
                                <AvatarFallback className={`bg-blue-400 text-white rounded-full`}>
                                    {user.name.charAt(0).toUpperCase()}
                                </AvatarFallback>
                            </Avatar>
                            {/*<img*/}
                            {/*    className={`size-11 rounded-full cursor-pointer hover:brightness-95`}*/}
                            {/*    src="/logo.png" alt="logo"/>*/}
                            <div className={`w-full divide-y divide-gray-200`}>
                                <div className={``}>
                            <textarea
                                value={value}
                                onChange={(e) => setValue(e.target.value)}
                                className={`w-full border-none focus:ring-0 text-lg placeholder-gray-500 tracking-wide
                                min-h-[50px] text-gray-700 p-2 placeholder:text-md`}
                                rows="2"
                                placeholder={`评论该贴`}></textarea>
                                    {selectedFileBase64 && (
                                        <div className={`relative`}>
                                            <XIcon
                                                onClick={() => {
                                                    setSelectedFile(null)
                                                    setSelectedFileBase64(null)
                                                }}
                                                className={`size-5 text-red-600 absolute cursor-pointer 
                                                        shadow-md shadow-white rounded-full`}/>
                                            {/*pulse闪烁动画*/}
                                            <img className={`size-14 ${loading && 'animate-pulse'}`}
                                                 src={selectedFileBase64}
                                                 alt=""/>
                                        </div>
                                    )}
                                </div>
                                <div className={`flex items-center justify-between pt-2.5`}>
                                    {!loading && (
                                        <>
                                            <div className={`flex`}>
                                                <div onClick={() => filePickerRef.current.click()}>
                                                    <PhotographIcon
                                                        className={`size-10 hoverEffect p-2 text-sky-500
                                                         hover:bg-sky-100`}/>
                                                    <input
                                                        accept={'image/*'}
                                                        type="file"
                                                        hidden
                                                        ref={filePickerRef}
                                                        onChange={addImageToComment}
                                                    />
                                                </div>
                                                <EmojiHappyIcon
                                                    className={`size-10 hoverEffect p-2 text-sky-500 
                                                    hover:bg-sky-100`}/>
                                            </div>
                                            <button
                                                onClick={sendComment}
                                                disabled={!value.trim()}
                                                className={`bg-blue-400 text-white px-4 py-1.5
                                                            rounded-full font-bold shadow-md 
                                                            hover:brightness-95 disabled:opacity-50`}
                                            >Reply
                                            </button>
                                        </>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
};

export default CommendModal;